package com.holy.sh.module_base_mvp.utils;


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import java.util.List;


public class TabFragmentUtils implements RadioGroup.OnCheckedChangeListener {
    private List<Fragment> fragments;
    private int containerLayout;
    private FragmentManager fragmentManager;
    private GetSelectIndex getSelectIndex;

    public TabFragmentUtils(RadioGroup radioGroup, List<Fragment> fragments, int containerLayout,
                            FragmentManager fragmentManager, GetSelectIndex getSelectIndex) {
        this.fragments = fragments;
        this.containerLayout = containerLayout;
        this.fragmentManager = fragmentManager;
        this.getSelectIndex=getSelectIndex;
        //对radioGroup设置监听
        radioGroup.setOnCheckedChangeListener(this);
        //默认选中第0个
        ((RadioButton) radioGroup.getChildAt(0)).setChecked(true);

    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        for (int i=0;i<group.getChildCount();i++){
            RadioButton view = ((RadioButton) group.getChildAt(i));
            if (view.getId()==checkedId){
                //显示相应的页码，隐藏其他的页码
                showFragmentByIndex(i);
            }
        }
    }
    private void showFragmentByIndex(int index) {
        getSelectIndex.getIndex(index);
        for (int i =0;i<fragments.size();i++){
            if (i==index){
                if (fragments.get(i).isAdded()){
                    fragmentManager.beginTransaction().show(fragments.get(i)).commitAllowingStateLoss();
                }else{
                    fragmentManager.beginTransaction().add(containerLayout,fragments.get(i)).commitAllowingStateLoss();
                }
            }else{
                if (fragments.get(i).isAdded()){
                    fragmentManager.beginTransaction().hide(fragments.get(i)).commitAllowingStateLoss();
                }
            }
        }
    }

   public interface GetSelectIndex{
        void getIndex(int index);
    }
}
